<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace web\api\controller;

/**
 * Class Finance
 * @package web\api\controller
 */
class Finance extends UserBase {

    /**
     * 会员金额数据
     */
    public function levelData(){
        try {
            $user_id = $this->user_id;
            $levelConfigM = new \addons\config\model\LevelConfig();
            $level_config_data = $levelConfigM->where(['level' => 1])->find();

            $user_data = $this->userM->getDetail($user_id);
            $balanceM = new \addons\member\model\Balance();
            $balance_amount = $balanceM->getBalanceAmountByType($user_id, self::USDT_TYPE);

            $data['level'] = $user_data['level'];
            $data['usdt_amount'] = $balance_amount;
            $data['level_data'] = $level_config_data;
            return $this->successJSON($data);
        } catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }

    /**
     * 开通会员
     */
    public function openingOfTheMember(){
        try {
            $user_id = $this->user_id;
            $balance_type = self::USDT_TYPE;
            $user_data = $this->userM->getDetail($user_id);
            if($user_data['level'] > 0){
                return $this->failJSON('您已是会员，请勿重复购买');
            }
            $balanceM = new \addons\member\model\Balance();
            $balance_amount = $balanceM->getBalanceAmountByType($user_id, $balance_type);
            $levelConfigM = new \addons\config\model\LevelConfig();
            $level_config_data = $levelConfigM->where(['level' => 1])->find();

            $price = $level_config_data['price'];
            if($balance_amount < $price){
                return $this->failJSON('金额不足');
            }

            $recordM = new \addons\member\model\TradingRecord();
            $balanceM->startTrans();

            $re_balance = $balanceM->updateBalance($user_id, $balance_type, $price, false);
            if(!$re_balance){
                $balanceM->rollback();
                return $this->failJSON('用户扣款失败');
            }

            $re_record = $recordM->addRecord($user_id, $price, $re_balance['before_amount'], $re_balance['amount'], $balance_type, 2000, 0, 0, '购买会员');
            if(!$re_record){
                $balanceM->rollback();
                return $this->failJSON('用户扣款记录失败');
            }

            $re = $this->userM->where(['id' => $user_data['id']])->update(['level' => $level_config_data['level'], 'update_time' => NOW_DATETIME]);
            if(!$re){
                $balanceM->rollback();
                return $this->failJSON('购买会员失败');
            }
            (new \addons\config\model\SystemMessage())->message_add($user_id, '购买会员','您的会员已到账，请及时前往查询',1);
            $balanceM->commit();
            $this->thridPush($user_id,$price);
            return $this->successJSON();
        } catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }

    /**
     * 视频判断是否购买了观看权限
     */
    public function videoPermissions(){
        try {
            $videoM = new \addons\video\model\Video();
            $id = $this->getParamVal('id');
            $video_data = $videoM->getDetail($id);
            //该视频是否要购买
            $data['is_pay'] = 0;
            $data['need_amount'] = $video_data['need_amount'];
            //该视频是否已购买
            $data['is_permissions'] = 0;
            if($video_data['need_amount'] > 0){
                $data['is_pay'] = 1;
                $videoPayM = new \addons\video\model\VideoPay();
                $pay_data = $videoPayM->where(['user_id' => $this->user_id, 'video_id' => $id, 'end_time' => ['>', date('Y-m-d H:i:s')]])->find();
                if($pay_data){
                    $data['is_permissions'] = 1;
                }
            }
            return $this->successJSON($data);
        } catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }

    /**
     * 购买视频
     */
    public function payVideo(){
        try {
            $id = $this->_post('id');
            $videoM = new \addons\video\model\Video();
            $video_data = $videoM->getDetail($id);
            if(empty($video_data)){
                return $this->failJSON('视频不存在');
            }

            $user_id = $this->user_id;
            $balance_type = self::USDT_TYPE;

            $videoPayM = new \addons\video\model\VideoPay();
            $pay_data = $videoPayM->where(['user_id' => $user_id, 'video_id' => $id, 'end_time' => ['>', date('Y-m-d H:i:s')]])->find();
            if($pay_data){
                return $this->failJSON('您已购买该视频，请勿重复购买');
            }

            $balanceM = new \addons\member\model\Balance();
            $balance_amount = $balanceM->getBalanceAmountByType($user_id, $balance_type);
            $price = $video_data['need_amount'];
            if($balance_amount < $price){
                return $this->failJSON('金额不足');
            }

            $recordM = new \addons\member\model\TradingRecord();
            $balanceM->startTrans();

            $re_balance = $balanceM->updateBalance($user_id, $balance_type, $price, false);
            if(!$re_balance){
                $balanceM->rollback();
                return $this->failJSON('用户扣款失败');
            }

            $re_record = $recordM->addRecord($user_id, $price, $re_balance['before_amount'], $re_balance['amount'], $balance_type, 2001, 0, 0, '购买付费视频');
            if(!$re_record){
                $balanceM->rollback();
                return $this->failJSON('用户扣款记录失败');
            }

            $re = $videoPayM->addData($user_id, $id, $price);
            if(!$re){
                $balanceM->rollback();
                return $this->failJSON('购买视频失败');
            }

            (new \addons\config\model\SystemMessage())->message_add($user_id, '购买付费视频','付费视频付费成功，请及时前往查询',1);
            $balanceM->commit();
            $this->thridPush($user_id,$price);
            return $this->successJSON();
        } catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }

    public function test(){
        // $this->thridPush(56,100);
    }
    /**
     * 三级会员释放
     */
    public function thridPush($user_id,$amount){
        $sysParameterM = new \web\common\model\sys\SysParameterModel();
        $push_data = $sysParameterM->getParameterDataByKey('2');
        $area_data = $sysParameterM->getParameterDataByKey('3');
        $balance_type = 1;
        $pid = $this->userM->where('id',$user_id)->value('pid');
        if(!$pid) return true;
        $balanceM = new \addons\member\model\Balance();
        $recordM = new \addons\member\model\TradingRecord();
        $balanceM->startTrans();
        $released_amount = bcmul($amount, $push_data['push_one']/100,8);
        $re_balance = $balanceM->updateBalance($pid, $balance_type, $released_amount, 1);
        if(!$re_balance){
            $balanceM->rollback();
            return $this->failJSON('用户加钱失败');
        }
        $re_record = $recordM->addRecord($pid, $released_amount, $re_balance['before_amount'], $re_balance['amount'], $balance_type, 50, 1, 0, '一级分销奖励');
        if(!$re_record){
            $balanceM->rollback();
            return $this->failJSON('用户加钱记录失败');
        }
        $ppid = $this->userM->where('id',$pid)->value('pid');
        if(!$ppid){
            $balanceM->commit();
            return true;
        }
        $released_amount = bcmul($amount, $push_data['push_two']/100,8);
        $re_balance = $balanceM->updateBalance($ppid, $balance_type, $released_amount, 1);
        if(!$re_balance){
            $balanceM->rollback();
            return $this->failJSON('用户加钱失败');
        }
        $re_record = $recordM->addRecord($ppid, $released_amount, $re_balance['before_amount'], $re_balance['amount'], $balance_type, 50, 1, 0, '二级分销奖励');
        if(!$re_record){
            $balanceM->rollback();
            return $this->failJSON('用户加钱记录失败');
        }
        $pppid = $this->userM->where('id',$ppid)->value('pid');
        if(!$pppid){
            $balanceM->commit();
            return true;
        }
        $released_amount = bcmul($amount, $push_data['push_three']/100,8);
        $re_balance = $balanceM->updateBalance($pppid, $balance_type, $released_amount, 1);
        if(!$re_balance){
            $balanceM->rollback();
            return $this->failJSON('用户加钱失败');
        }
        $re_record = $recordM->addRecord($pppid, $released_amount, $re_balance['before_amount'], $re_balance['amount'], $balance_type, 50, 1, 0, '三级分销奖励');
        if(!$re_record){
            $balanceM->rollback();
            return $this->failJSON('用户加钱记录失败');
        }
        $balanceM->commit();
        $this->areaPush($user_id,$amount,$balanceM,$recordM);
        return true;
    }


    /**
     * 三级会员释放
     */
    public function areaPush($user_id,$amount,$balanceM,$recordM){
        $sysParameterM = new \web\common\model\sys\SysParameterModel();
        $area_data = $sysParameterM->getParameterDataByKey('3');
        $balance_type = 1;
        $pid_path = $this->userM->where('id',$user_id)->value('pid_path');
        $list = $this->userM->field('id,level')->where(['id'=>['in',$pid_path]])->order('id desc')->select();
        $arr = [
            ['level'=>1,'rate'=>$area_data['area_release']],
            ['level'=>2,'rate'=>$area_data['city_release']],
            ['level'=>3,'rate'=>$area_data['province_release']],
        ];
        // dd($arr);
        $res = $this->gradation($list,$arr);
        foreach ($res as $k => $v) {
            $balanceM->startTrans();
            $released_amount = bcmul($amount, $v['rate']/100,8);
            $re_balance = $balanceM->updateBalance($v['user_id'], $balance_type, $released_amount, 1);
            if(!$re_balance){
                $balanceM->rollback();
                return $this->failJSON('用户加钱失败');
            }
            $re_record = $recordM->addRecord($v['user_id'], $released_amount, $re_balance['before_amount'], $re_balance['amount'], $balance_type, 51, 1, 0, $v['level'].'省市区分销');
            if(!$re_record){
                $balanceM->rollback();
                return $this->failJSON('用户加钱记录失败');
            }
            $balanceM->commit();
        }
        return true;
    }



    /**
     * 极差制度
     */
    public function gradation($list,$rate_arr){
        // echo "in gradation \n";
        //设置不同等级的利率   与领取的状态
        $name = 'rec';
        $max_level = 0;
        $arr = [];
        $count = count($rate_arr);
        foreach ($rate_arr as $key => $v) {
            if($max_level<$v['level']) $max_level = $v['level'];
            $arr[$v['level']] = $v['rate'];
            $cap = $name.$v['level'];
            $$cap = 0;
        }
        $new = [];
        $rate = 0;
        $key = 1;
        foreach ($list as $k => $v) {
            $cap = $name.$v['level'];
            if(!isset($$cap)) continue;
            //未领取
            if($$cap==0){
                //判断利率是否存在
                if(isset($rate_arr[$count-$key])){
                    //最大判断
                    $is_receive = $name.$rate_arr[$count-1]['level'];
                    if($$is_receive>0) continue;
                    //次级发放判断
                    if(($v['level']+1)>$max_level){
                        $is_receive = $name.$max_level;
                    }else{
                        $is_receive = $name.($v['level']+1);
                    }
                    if($$is_receive>0) continue;
                    $is_level_receive = $name.($v['level']-1);
                    if(isset($$is_level_receive)&&$$is_level_receive>0){
                        $rate = $arr[$v['level']]-$arr[$v['level']-1];
                    }else{
                        $rate = $arr[$v['level']]-$rate;
                    }
                    if(isset($v['user_id'])) $tmp['user_id'] = $v['user_id'];
                    else $tmp['user_id'] = $v['id'];
                    $tmp['rate'] = abs($rate);
                    $tmp['level'] = $v['level'];
                    $tmp['type'] = 1;
                    // echo "count:{$count} | key:{$key} | rate:{$rate} | user_id:{$tmp['user_id']} | level:{$v['level']} | rate:{$tmp['rate']}<br>";
                    $new[] = $tmp;
                    $$cap = 1;
                    $key++;
                    $last_level = $v['level']-1;
                    $ccap = $name.$last_level;
                    if(isset($$ccap)) $$ccap = 2;
                    continue;
                }else{
                    continue;
                }
            }
            //平级奖
            if($$cap==1){
                continue;
                if(isset($v['user_id'])) $tmp['user_id'] = $v['user_id'];
                else $tmp['user_id'] = $v['id'];
                $tmp['level'] = $v['level'];
                $tmp['type'] = 2;
                $new[] = $tmp;
                $$cap = 2;
                continue;
            }
            //都领取过
            if($$cap>1){
                continue;
            }
        }
        // echo "end \n";
        return $new;
    }

    /**********************************/

    /**
     * 转账手续费
     */
    public function transferTax(){
        $accountM = new \addons\member\model\MemberAccountModel();
        $level = $accountM->where('id',$this->user_id)->value('level');
        $data['is_operation'] = 0;
        $data['fee'] = 0;
        $data['gx_amount'] = 0;
        if($level > 0){
            $data['is_operation'] = 1;
            $level_data =(new \addons\member\model\LevelConfig())->where(['level' => $level])->find();
            $amount = $this->_post('amount');
            $data['fee'] = round(($amount * $level_data['poundage_rate'] / 100), 2);
            $sysParameterM = new \web\common\model\sys\SysParameterModel();
            $price = $sysParameterM->getValByName('dc_price');
            $data['gx_amount'] = $amount * $price;
        }
        return $this->successJSON($data);
    }

    /**
     * 转账
     */
    public function transfer(){
        try{
            $to_address = $this->getParamVal("to_address");
            $amount = $this->getParamVal("amount");
            // $balance_type = $this->getParamVal("balance_type");
            $balance_type = 1;
            // $pay_password = $this->getParamVal("pay_password");
            // if($pay_password == '') return $this->failJSON('请输入交易密码');
            if($to_address == '') return $this->failJSON('请输入需要转账的手机号');
            $sysParameterM = new \web\common\model\sys\SysParameterModel();
            $transfer_min = $sysParameterM->getValByName('transfer_min');
            if($transfer_min > 0){
                if($amount < $transfer_min) return $this->failJSON('最低转账数量'.$transfer_min);
            }
            $user_id = $this->user_id;
            $accountM = new \addons\member\model\MemberAccountModel();
            $balanceM = new \addons\member\model\Balance();
            $recordM = new \addons\member\model\TradingRecord();
            $to_user_data = $accountM->where(['trc_address' => $to_address])->find();
            if(!$to_user_data) return $this->failJSON('地址不存在');
            if($to_user_data['id'] == $user_id) return $this->failJSON('不能转给自己');
            // $user_data = $accountM->checkPayPwdLevel($user_id,$pay_password);
            // if(!$user_data) return $this->failJSON('交易密码错误');
            // $verify_code = $this->getParamVal('verify_code');
            // $verifyM = new \addons\member\model\VericodeModel();
            // $_verify = $verifyM->VerifyCode($verify_code, $user_data['phone'], 5, $user_data['country_code']);
            // if (empty($_verify)) {
            //     return $this->failJSON(lang('MEMBER_CODE_WRONG'));
            // }
            $balanceM->startTrans();
            //usdt的转账
            if($balance_type == 1){
                $user_balance = $balanceM->getBalanceAmountByType($user_id, $balance_type);
                if($user_balance < $amount){
                    return $this->failJSON('余额不足');
                }
                $re_balance = $balanceM->updateBalance($user_id, $balance_type, $amount, false);
                if(!$re_balance){
                    $balanceM->rollback();
                    return $this->failJSON('用户扣款失败');
                }
                $re_record = $recordM->addRecord($user_id, $amount, $re_balance['before_amount'], $re_balance['amount'], $balance_type, 4, 0, $to_user_data['id'], '转账');
                if(!$re_record){
                    $balanceM->rollback();
                    return $this->failJSON('用户扣款记录失败');
                }

                //增加转账的用户金额
                $re_balance = $balanceM->updateBalance($to_user_data['id'], $balance_type, $amount, true);
                if(!$re_balance){
                    $balanceM->rollback();
                    return $this->failJSON('用户增加金额失败');
                }

                $trc_address = $accountM->getDetail($user_id, 'trc_address')['trc_address'];
                $re_record = $recordM->addRecord($to_user_data['id'], $amount, $re_balance['before_amount'], $re_balance['amount'], $balance_type, 4, 1, $user_id, '转账,对方：'.$trc_address);
                if(!$re_record){
                    $balanceM->rollback();
                    return $this->failJSON('用户增加金额记录失败');
                }
            }
            $balanceM->commit();
            return $this->successJSON();
        }catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }

    /**
     * 贡献值记录
     */
    public function recordList() {
        try {
            $recordM = new \addons\member\model\TradingRecord();
            $filter = ' user_id=' . $this->user_id .' and a.type = 4 ';
            $fileds = 'a.id,a.asset_type,a.update_time,a.change_type,a.amount,a.type,a.remark,trt.type_name,c.username to_username';
            $list = $recordM->getTradingRecordList($this->getPageIndex(), $this->getPageSize(), $filter, $fileds);
            return $this->successJSON($list);
        } catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }

    /**
     * 锁仓列表
     */
    public function lockUpList(){
        try{
            $lockUpM = new \addons\equip\model\LockUp();
            $data['usdt_total_amount'] = $lockUpM->where(['user_id' => $this->user_id, 'balance_type' => 1, 'type' => 1, 'status' => 0])->sum('amount')??0;
            $data['dc_total_amount'] = $lockUpM->where(['user_id' => $this->user_id, 'balance_type' => 2, 'type' => 1,  'status' => 0])->sum('amount')??0;
            $data['kof_total_amount'] = $lockUpM->where(['user_id' => $this->user_id, 'balance_type' => 3, 'type' => 1,  'status' => 0])->sum('amount')??0;
            $data['agent_total_amount'] = $lockUpM->where(['user_id' => $this->user_id, 'balance_type' => 2, 'type' => 2,  'status' => 0])->sum('amount')??0;
            $data['dc_hope_total_amount'] = $lockUpM->where(['user_id' => $this->user_id, 'balance_type' => 2, 'type' => 3,  'status' => 0])->sum('amount')??0;
            $data['hope_total_amount'] = $lockUpM->where(['user_id' => $this->user_id, 'balance_type' => 3, 'type' => 3,  'status' => 0])->sum('amount')??0;

            return $this->successJSON($data);
        }catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }

    /**
     * 锁仓币种详细列表
     */
    public function lockUpBalanceList(){
        try{
            $type = $this->_post('type');
            if($type == '' || $type == null){
                $type = 1;
            }
            $balance_type = $this->_post('balance_type');
            $lockUpM = new \addons\equip\model\LockUp();

            $filter = 'status = 0 and user_id = '.$this->user_id .' and type = '.$type ;

            if($balance_type != null || $balance_type != ''){
                $filter .= ' and balance_type = '. $balance_type;
            }

            $list = $lockUpM->getDataList($this->getPageIndex(), $this->getPageSize(), $filter, '*');
            if($list){
                foreach ($list as &$value){
                    $value['released_amount'] = round(($value['amount'] - $value['remaining_amount']), 4);
                }
            }
            return $this->successJSON($list);
        }catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }



    /****************************************/
    /**
     * 兑换数据
     */
    public function exchangeTax(){
        try{
            $sysParameterM = new \web\common\model\sys\SysParameterModel();
            $data['umkxz_price'] = $sysParameterM->getValByName('umkxz_price');
            $data['umk_price'] = $sysParameterM->getValByName('umk_price');
            $data['usdt_price'] = $sysParameterM->getValByName('usdt_price');
            $data['price_now'] = (new \addons\config\model\Quotation)->where('type',2)->order('create_at desc')->value('price_now');
            return $this->successJSON($data);
        }catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }

    /**
     * 发起闪兑
     */
    public function flashExchange(){
        try{
            $type = $this->getParamVal('type');
            $amount = $this->getParamVal('amount');

            $sysParameterM = new \web\common\model\sys\SysParameterModel();
            $umk_price = $sysParameterM->getValByName('umk_price');

            $exchange_min = $sysParameterM->getValByName('exchange_min');
            $exchange_tax = $sysParameterM->getValByName('exchange_tax');
            if($exchange_min > 0) {
                if($amount < $exchange_min) return $this->failJSON('最低兑换：'.$exchange_min);
            }

            $price_now = (new \addons\config\model\Quotation)->where('type',2)->order('create_at desc')->value('price_now');

            $balanceM = new \addons\member\model\Balance();
            if($type == 1){
                $balance_type = self::PT_TYPE;
                $ultimately_amount = $amount * $price_now;
                $to_balance_type = self::USDT_TYPE;
            }else if($type == 2){
                $balance_type = self::PT_TYPE;
                $ultimately_amount = $amount * $price_now / $umk_price;
                $to_balance_type = self::UMK_TYPE;
            }else if($type == 3){
                $balance_type = self::USDT_TYPE;
                $ultimately_amount = $amount / $umk_price;
                $to_balance_type = self::UMK_TYPE;
            }else if($type == 4){
                $balance_type = self::UMK_TYPE;
                $ultimately_amount = $amount * $umk_price;
                $to_balance_type = self::USDT_TYPE;
            }else{
                $balance_type = self::USDT_TYPE;
                $ultimately_amount = $amount / $price_now;
                $to_balance_type = self::PT_TYPE;
            }

            $fee = 0;
            $remark = '';
            if($exchange_tax > 0){
                $fee = $amount * $exchange_tax / 100;
                $remark = '，手续费:'.$fee;
            }

            $total_amount = $amount + $fee;

            $user_amount = $balanceM->getBalanceAmountByType($this->user_id, $balance_type);
            if($user_amount < $total_amount) return $this->failJSON('余额不足');

            $balanceM->startTrans();

            //扣除金额
            $re_balance = $balanceM->updateBalance($this->user_id, $balance_type, $total_amount, false);
            if(!$re_balance){
                $balanceM->rollback();
                return $this->failJSON('用户扣款失败');
            }
            $recordM = new \addons\member\model\TradingRecord();
            $re_record = $recordM->addRecord($this->user_id, $total_amount, $re_balance['before_amount'], $re_balance['amount'], $balance_type, 100, 0, 0, '闪兑'.$remark);
            if(!$re_record){
                $balanceM->rollback();
                return $this->failJSON('用户扣款记录失败');
            }

            //增加金额
            $re_balance = $balanceM->updateBalance($this->user_id, $to_balance_type, $ultimately_amount, true);
            if(!$re_balance){
                $balanceM->rollback();
                return $this->failJSON('用户增加金额失败');
            }
            $recordM = new \addons\member\model\TradingRecord();
            $re_record = $recordM->addRecord($this->user_id, $ultimately_amount, $re_balance['before_amount'], $re_balance['amount'], $to_balance_type, 100, 1, 0, '闪兑');
            if(!$re_record){
                $balanceM->rollback();
                return $this->failJSON('用户增加金额记录失败');
            }
            $balanceM->commit();
            return $this->successJSON();

        }catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }


/**************************************/

    /**
     * 闪兑
     */
    public function flashExchange1(){
        $memberM = new \addons\member\model\MemberAccountModel();
        $balanceM = new \addons\member\model\Balance();
        $sysConfigM = new \web\common\model\sys\SysParameterModel();
        $recordM = new \addons\member\model\TradingRecord();

        $pay_password = $this->_post('pay_password');
        $bool = $memberM->checkPayPwd($this->user_id,$pay_password);
        if (!$bool) return $this->failJSON(lang('FINANCE_WRONG_PAYPASSWORD'));

        $type = $this->_post('type');
        //1-USDT>SPD   2-SPD->USDT
        if($type==1){
            $balance_amount = $balanceM->getBalanceAmountByType($this->user_id, 2);
            $name = 'USDT';
        }elseif($type==2){
            $name = 'SPD';
            $balance_amount = $balanceM->getBalanceAmountByType($this->user_id, 3);
        }else{
            return $this->failJSON(lang('FINANCE_EXCHANGE'));    
        }
        //兑换总数量
        $amount = $this->_post('amount');
        if($amount <= 0){
            return $this->failJSON(lang('FINANCE_QUANTITY'));
        }

        // $sys_data = $sysConfigM->getParameterDataByKey(6);
        // $price_now = (new \addons\config\model\Quotation)->where('type',3)->order('create_at desc')->value('price_now');
        // $usdt_price = $sysConfigM->getValByName('usdt_price');
        // $sys_data['usdt_to_spd'] = bcmul($price_now, $usdt_price,4);
        // $sys_data['spd_to_usdt'] = bcdiv(1, $sys_data['usdt_to_spd'],4);
        $sys_data = [];
        $price_now = (new \addons\config\model\Quotation)->where('type',3)->order('create_at desc')->value('price_now');
        $usdt_price = $sysConfigM->getValByName('usdt_price');
        $sys_data['usdt_to_spd'] = bcdiv(1, $price_now,4);
        $sys_data['spd_to_usdt'] = bcdiv(1, $sys_data['usdt_to_spd'],4);
        $sys_data['usdt_to_spd_rate'] = 0;
        $sys_data['spd_to_usdt_rate'] = $this->getChangeFee();

        if($type==1){
            $is_tax = $sys_data['usdt_to_spd_rate'];
            $limit_amount = $sysConfigM->getValByName('asset_exchange_1');
            if($limit_amount>$amount){
                return $this->failJSON($name.lang('FINANCE_LIMIT_EXCHANGE').$limit_amount);
            }
            $to_amount = bcmul($amount, $sys_data['usdt_to_spd'],4);
            $coin_type = 2;
            $to_coin_type = 3;
            $remark = 'USDT兑换SPD 比例1:'.$sys_data['usdt_to_spd'];
        }else{
            $limit_amount = $sysConfigM->getValByName('asset_exchange_2');
            if($limit_amount>$amount){
                return $this->failJSON($name.lang('FINANCE_LIMIT_EXCHANGE').$limit_amount);
            }
            $user_data = $memberM->getDetail($this->user_id);
            $is_tax = $sys_data['spd_to_usdt_rate'];
            $to_amount = bcmul($amount, $sys_data['spd_to_usdt'],4);
            $coin_type = 3;
            $to_coin_type = 2;
            $remark = 'SPD兑换USDT 比例1:'.$sys_data['spd_to_usdt'];
        }

        $fee = bcmul($is_tax/100, $amount,4);
        $total_amount = bcadd($amount, $fee,4);
        if($total_amount>$balance_amount){
            return $this->failJSON($name.lang('FINANCE_BALANCE'));
        }

        $balanceM->startTrans();
        try {
            //资金变化流水类型
            $record_type = 6;
            //扣除兑换元气豆用都usdt
            $re_balance = $balanceM->updateBalance($this->user_id, $coin_type, $total_amount, false);
            if(!$re_balance){
                $balanceM->rollback();
                return $this->failJSON(lang('FINANCIAL_BUY_6'));
            }
            if($fee>0){
                $res = (new \addons\member\model\DailyBonus)->addBonus($fee);
                if(!$res){
                    $balanceM->rollback();
                    return $this->failJSON(lang('FINANCE_ADD_POOL'));
                }
            }
            $re_record = $recordM->addRecord($this->user_id, $total_amount, $re_balance['before_amount'], $re_balance['amount'], $coin_type, $record_type, 0 , 0, $remark);
            if(!$re_record){
                $balanceM->rollback();
                return $this->failJSON(lang('TRADE_LOG_FAIL'));
            }

            $re_balance = $balanceM->updateBalance($this->user_id, $to_coin_type, $to_amount, true);
            if(!$re_balance){
                $balanceM->rollback();
                return $this->failJSON(lang('OTC_AMOUNT_ADD'));
            }
            $re_record = $recordM->addRecord($this->user_id, $to_amount, $re_balance['before_amount'], $re_balance['amount'], $to_coin_type, $record_type, 1 , 0, $remark);
            if(!$re_record){
                $balanceM->rollback();
                return $this->failJSON(lang('EQUIP_ADD_RECORD'));
            }
            $balanceM->commit();
            return $this->successJSON();
        } catch (\Exception $ex) {
            return $this->failJSON($ex->getMessage());
        }
    }


    /**
     * 行情
     */
    public function quotationKline(){
        $tickerId = $this->_get('symbol');
        // $tickerId = 'icon';
        $period = $this->_get('period');
        $keys = 'quotation'.$tickerId.$period;
        $arr = $this->globalCache->get($keys);
        if($arr) return $this->successJSON($arr);
        $dates = [];
        $data = [];
        $volumes = [];
        if($tickerId=='icon'){
            $url = "http://api.zb.live/data/v1/kline?market=icx_usdt&type=1day";
            $res = http($url);
            if($res['success']){
                $array = $res['data']['data'];
                krsort($array);
                foreach ($array as $key => $v) {
                    $dates[] = date('Y-m-d',$v[0]/1000);
                    // $tmp = [$v[1],$v[4],$v[3],$v[2],$v[5]];
                    $data[] = $v[1];
                    // $volumes[] = $v[5];
                }
            }
            
        }else{
            $HotApi = new \web\common\utils\HotApi();
            $info = $HotApi->get_history_kline($tickerId,$period);
            if(!$info['success']) return $this->failJSON(lang('FINANCE_ADD_RECORD'));
            foreach ($info['data']['data'] as $key => $v) {
                $dates[] = date('Y-m-d',$v['id']);
                // $tmp = [$v['open'],$v['close'],$v['low'],$v['high'],$v['vol']];
                $data[] = $v['open'];
                // $volumes[] = $v['vol'];
            }
        }

        $r['dates'] = $dates;
        $r['data'] = $data;
        // $r['volumes'] = $volumes;
        $this->globalCache->set($keys,$r,300);
        return $this->successJSON($r);
    }

    /**
     * 获取行情列表
     */
    public function quotationList(){
        $keys = 'quotationList';
        $arr = $this->globalCache->get($keys);
        // if($arr) return $this->successJSON($arr);
        $HotApi = new \web\common\utils\HotApi();
        $arr = $HotApi->get_tickers();
        $new = [];
        foreach ($arr['data']['data'] as $key => $v) {
            if(in_array($v['symbol'], ['btcusdt','ethusdt','xrpusdt','bchusdt','bsvusdt','ltcusdt','eosusdt','etcusdt','adausdt','trxusdt'])){
                $v['name'] = strtoupper(str_replace('usdt', '', $v['symbol']));
                $v['rate'] = bcdiv(($v['close']-$v['open'])*100, $v['open'],2);
                if(($v['close']-$v['open'])>0){
                    $v['rate'] = '+'.$v['rate'];
                    $v['d_type'] = 0;
                }else{
                    $v['d_type'] = 1;
                }
                $v['amount'] = bcmul($v['vol'], 1,2);
                $v['open'] = $v['ask'];
                $new[] = $v;
            }
        }
        $this->globalCache->set($keys,$new,300);
        return $this->successJSON($new);
    }

    public function coinKline(){
        $coin_type = $this->_post('coin_type');
        $keys = 'coinKline'.$coin_type;
        $arr = $this->globalCache->get($keys);
        if($arr) return $this->successJSON($arr);
        $dates = [];
        $data = [];
        if($coin_type=='3'){
            $list = (new \addons\config\model\Quotation())->where('type',$coin_type)->field('price_now open,create_at time')->order('create_at desc')->select();
            foreach ($list as $key => $v) {
                $dates[] = $v['time'];
                $data[] = $v['open'];
            }

        }elseif($coin_type=='4'){
            $HotApi = new \web\common\utils\HotApi();
            $info = $HotApi->get_history_kline('ethusdt','1day');
            if(!$info['success']) return $this->failJSON(lang('FINANCE_ADD_RECORD'));
            foreach ($info['data']['data'] as $key => $v) {
                $dates[] = date('Y-m-d',$v['id']);
                $data[] = 1;
            }
        }elseif($coin_type==1){
            $HotApi = new \web\common\utils\HotApi();
            $info = $HotApi->get_history_kline('ethusdt','1day');
            if(!$info['success']) return $this->failJSON(lang('FINANCE_ADD_RECORD'));
            foreach ($info['data']['data'] as $key => $v) {
                $dates[] = date('Y-m-d',$v['id']);
                $data[] = $v['open'];
            }
        }elseif($coin_type==2){
            $HotApi = new \web\common\utils\HotApi();
            $info = $HotApi->get_history_kline('ethusdt','1day');
            if(!$info['success']) return $this->failJSON(lang('FINANCE_ADD_RECORD'));
            foreach ($info['data']['data'] as $key => $v) {
                $dates[] = date('Y-m-d',$v['id']);
                $data[] = 1;
            }
        }

        $r['dates'] = $dates;
        $r['data'] = $data;
        $this->globalCache->set($keys,$r,3600);
        return $this->successJSON($r);
    }


    /**
     * 系统行情列表
     */
    public function coinList(){
        // $coin_type = $this->_post('coin_type');
        $keys = 'coinList';
        $arr = $this->globalCache->get($keys);
        if($arr) return $this->successJSON($arr);
        $list = (new \addons\config\model\Quotation())->field('price_now open,create_at time')->order('create_at asc')->select();
        $this->globalCache->set($keys,$list,1800);
        return $this->successJSON($list);
    }


}
